package com.lyy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.lyy.entity.User;
import com.lyy.mapper.UserMapper;
import com.lyy.service.UserService;
import com.lyy.MinioUtil;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * @author Liangyaoyun
 */
@Data
public class UserServiceImpl implements UserService {
     private UserMapper userMapper;
    @Override
    public int insertByUserId(User user) {
        return userMapper.insertByUserId(user);
    }

    @Override
    public int updateByUserId(User user) {
        return userMapper.updateByUserId(user);
    }

    @Override
    public int deleteByUserId(Integer userId) {
        return userMapper.deleteByUserId(userId);
    }

    @Override
    public User selectByUserId(Integer userId) {
        return userMapper.selectByUserId(userId);
    }

    @Override
    public int deleteByUserIds(List<Integer> userId) {
        return userMapper.deleteByUserIds(userId);
    }

    @Override
    public List<User> selectAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public PageInfo<User> selectBypage(Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber,pageSize);
        return new PageInfo<>(userMapper.selectAllUser());
    }

    @Override
    public User login(String username, String password) {
        User admin=userMapper.selectByUserId(1);
        String adminUsername=admin.getUsername();
        String adminPassword=admin.getPassword();
        if (username.equals(adminUsername)&&adminPassword.equals(password)){
            return admin;
        }
        return null;
    }
    @Override
    public int todayCount() {
        return userMapper.todayCount();
    }
    @Override
    public int totalCount() {
        return userMapper.totalCount();
    }
    @Override
    public List<Map<String, Integer>> genderCount(){
        return userMapper.genderCount();
    }
    @Override
    public List<Map<String, Integer>> growthCount(){
        return userMapper.growthCount();
    }
    @Override
    public int uploadAvatar(MultipartFile avatarFile, Integer userId) {
        // 查询旧图片
        User user = userMapper.selectByUserId(userId);
        if (null == user) {
            throw new RuntimeException("轮播图不存在");
        }
        String avatarUrl = user.getAvatarUrl();
        // 从MINIO中删除旧图片: 默认图片不删除
        if (!"default-user.jpg".equals(avatarUrl)) {
            MinioUtil.delete(avatarUrl, "avatar");
        }
        // 向MINIO中上传新图片
        String avatarFileName = MinioUtil.upload(avatarFile, "avatar");
        User userPo = new User();
        userPo.setUserId(userId);
        userPo.setAvatarUrl(avatarFileName);
        return userMapper.updateByUserId(userPo);
    }
}
